<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>手动实现拖拽</title>
    <style>
        .move{
            position: absolute;
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
    <div class="move"></div>

    <script type="module">
        let el = document.querySelector('.move');
        let dragging = false; // 拖拽状态
        let left, top; // 鼠标按下时相对于元素的移位

        document.addEventListener('mousedown', function(e) {
            console.log(e)
            if (e.target === el) {
                dragging = true; // 激活拖拽状态
                let elRect = el.getBoundingClientRect(); // 返回元素的大小以及视口的位置
                console.log(elRect)
                left = e.clientX - elRect.left; // x坐标偏移
                top = e.clientY - elRect.top; // y坐标偏移
                console.log(left, top)
            }
        })

        document.addEventListener('mouseup', function(e) {
            dragging = false;
        })

        document.addEventListener('mousemove', function(e) {
            if (dragging) {
                let moveX = e.clientY - left;
                let moveY = e.clientY - top;

                el.style.left = moveX + 'px';
                el.style.top = moveY + 'px';
            }
        })
    </script>
</body>
</html>